package com.sdemo.modules.sys.controller;


import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.sdemo.common.globals.Globals;
import com.sdemo.modules.comm.controller.BaseController;
import com.sdemo.modules.sys.model.Menu;
import com.sdemo.modules.sys.model.Role;
import com.sdemo.modules.sys.model.User;
import com.sdemo.modules.sys.service.impl.RoleServiceImpl;
import com.sdemo.modules.sys.service.impl.UserServiceImpl;
import com.sdemo.utils.Convert;
import com.sdemo.utils.MD5;
import com.sdemo.utils.Pager;
import com.sdemo.utils.Ret;
import com.sdemo.utils.ThreadPoolUtil;
import com.sdemo.utils.jedis.MyJedis;
import com.sdemo.utils.mq.activemq.ActiveMQProducer;
import com.sdemo.utils.mq.activemq.JMSMode;

@Controller
@RequestMapping("/sys")
public class UserController extends BaseController {
	@Autowired
	private UserServiceImpl userServiceImpl; 
	@Autowired
	private RoleServiceImpl roleServiceImpl; 
	
	 //注入jsmtemplate
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

   
    
	@RequestMapping(value={"/queryUserById"})
	@ResponseBody
	public Ret queryUserById(Long userId){
		User user = userServiceImpl.queryUserById(userId);
		//登陆的用户id:getUserId()
		//点击的userID:userId
		  List<Role> rolelist = roleServiceImpl.queryRoleAll(getUserId(), userId);
		   	for(int i=0;i<rolelist.size();i++){
		   		Role role = rolelist.get(i);
		   		if(role.getRcount()>=2){
		   			//rolelist.get(i).setRcount(2);//
		   			rolelist.get(i).setCheckeds(2);//需要打钩的
		   		}
		   		if(role.getUserId().longValue()==userId.longValue()){
		   			//rolelist.get(i).setRcount(2);//
		   			rolelist.get(i).setCheckeds(2);//需要打钩的
		   		
		   		}
		   	}
		if(user == null){
			Ret.error("数据为空");
		}
		return Ret.ok().put("data", user).put("rolelist", rolelist);
	}
	
   @RequestMapping(value={"/userlist"})
   @ResponseBody
   //@RequiresPermissions(value={"sys:man:user"})//权限控制
   public  Pager<User> userlist(HttpServletRequest request){
	   
	   Map<String, Object> parms = super.getParamValues(request);
	   
	   parms =super.pageXX(parms, request);
	   
	   
	   List<User> userList = userServiceImpl.queryPageUser(parms);
	   int total = userServiceImpl.queryCount(parms);
	   Pager<User> page = new Pager<User>();
	   page.setRows(userList);
	   page.setTotal(total);
	    ActiveMQQueue activeMQQueue = new ActiveMQQueue(Globals.queue_usermsg);
	   for(int i=0;i<page.getRows().size();i++){
		   User user=  page.getRows().get(i);
		   jmsMessagingTemplate.convertAndSend(activeMQQueue,JSONObject.toJSONString(user) );
	   }
	  
       return page;
   }
   
   @RequestMapping(value={"/user/updatalist"})
   @ResponseBody
   
   public Ret updataUser(User user,String roleIds){
	   String[] arrStr = roleIds.split(",");
	   List<User> list = new ArrayList<>();
	   for(int i=0;i<arrStr.length;i++){
		   User ruser = new User();
		   ruser.setRoleid(Convert.getLong(arrStr[i]));
		   ruser.setUserId(user.getUserId());
		   list.add(ruser);
	   }
	   try {
		   userServiceImpl.deleteUserRole(user.getUserId());
		   userServiceImpl.insertUserRoleBath(list);
		   userServiceImpl.updateUser(user);
		   myJedis.hdel(Globals.redis_userauth_key, Globals.redis_userid_key.concat(String.valueOf(user.getUserId())));
		} catch (Exception e) {
			logger.error("updatalist error:{}",e);
			 return Ret.error();
		}
	   return Ret.ok();
   }
   
   @RequestMapping(value={"user/sys/deleteUser"})
   @ResponseBody
   //@RequiresPermissions(value={"sys:man:del"})//权限控制
   public Ret deleteUser(User user,Long userId){
	   //System.out.println(user.getUsername()+"-----"+user.getNickname()+"------"+user.getStatus()+"----"+user.getUserId());
	   int index = userServiceImpl.deleteUser(userId);
	   Ret ret = new Ret();
	   if(index>0){
		   ret.put("code", 0); 
	   }
	   return ret;
   }
   
 
   @RequestMapping(value={"/insertUserByUsername"})
   @ResponseBody
   @RequiresPermissions(value={"sys:man:add"})//权限控制
   public Ret insertUserByUsername(User user){
	   User users = userServiceImpl.queryUserByUsername(user.getUsername());  
	   if(users != null){
		   return Ret.error("用户名已存在或输入错误!");
	   }
	   user.setPassword(MD5.getMD5("123456"));
	   userServiceImpl.insertUserByUsername(user);

	   String[] arrStr = user.getRoleIds().split(",");
	   List<User> list = new ArrayList<>();
	   for(int i=0;i<arrStr.length;i++){
		   User ruser = new User();
		   ruser.setRoleid(Convert.getLong(arrStr[i]));
		   ruser.setUserId(user.getUserId());
		   list.add(ruser);
	   }
	   int index =  userServiceImpl.insertUserRoleBath(list);
	   ThreadPoolUtil.getInstance().execute(new Runnable() {
		@Override
		public void run() {
				ActiveMQProducer producer = ActiveMQProducer.getInstance("Queue.HQ", "producer", JMSMode.QUEUE, true);
				producer.send(JSONObject.toJSONString(user).getBytes());
			
			}
	   });

	   return Ret.ok();
   }
   @RequestMapping("/getguserInfo")
	@ResponseBody
	public Ret getuserInfo(){
		try {
			 List<Menu> list = roleServiceImpl.queryAuthByRoleid(getUserId());
	            Set<String> set = new HashSet<>();
	            for(int i = 0 ; i < list.size(); i++){
	            	 set.add(list.get(i).getAuthvalue());
	            }
	            return Ret.ok("").put("auth", set); 
		} catch (Exception e) {
			logger.error("login error",e);
			return Ret.error("出错了");
		}		
	}
   
   
   
   @RequestMapping(value={"/downExceluser"})
   public void downExcel(HttpServletRequest request, HttpServletResponse response){
	   
	   Map<String, Object> parms = super.getParamValues(request);
	   parms =super.pageXX(parms, request);
	   List<User> userList = userServiceImpl.queryPageUser(parms);
 
	   try {
		   HSSFWorkbook wb = userExportService(userList);  
	       response.setContentType("application/vnd.ms-excel");  
	       response.setHeader("Content-disposition", "attachment;filename=user.xls");  
	       OutputStream ouputStream = response.getOutputStream();  
	       wb.write(ouputStream);  
	       ouputStream.flush();  
	       ouputStream.close();  
		} catch (Exception e) {
			e.printStackTrace();
		}
     
   }
   
   private HSSFWorkbook userExportService(List<User> list){
	   
	   String[] excelHeader = { "userId", "用户名", "昵称"};
	   
	   
	   HSSFWorkbook wb = new HSSFWorkbook();  
       HSSFSheet sheet = wb.createSheet("user1");  
       HSSFRow row = sheet.createRow((int) 0);  
       HSSFCellStyle style = wb.createCellStyle();  
 
       for (int i = 0; i < excelHeader.length; i++) {  
           HSSFCell cell = row.createCell(i);  
           cell.setCellValue(excelHeader[i]);  
           cell.setCellStyle(style);  
           sheet.autoSizeColumn(i);  
        // sheet.SetColumnWidth(i, 100 * 256);  
       }  
 
       for (int i = 0; i < list.size(); i++) {  
           row = sheet.createRow(i + 1);  
           User user = list.get(i);  
           row.createCell(0).setCellValue(user.getUserId());  
           row.createCell(1).setCellValue(user.getUsername());  
           row.createCell(2).setCellValue(user.getNickname());  
       }  
       return wb;  
   }



}
